define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('A0801Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$calculater', '$timeout',"$compile",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater, $timeout,$compile) {
                
            this.init = function (plotItem,plot_no, parent,items,machine_detail,parentIndex,index,unDispatchItem,lst_opno,machine, feedback) {
                 
                // 产品编号，作业站编号,产品版本 过滤
               var hasValue = false; // 匹配到建議派工量
               items.lst_ORM_EquipmentPeriodModel.forEach(item=>{
                  
                 if(item.suggest_detail.length > 0){
                        item.suggest_detail.forEach(flag=>{
                           if(plotItem.op_no == flag.OPNO &&plotItem.item_no == flag.PRODUCTNO&& plotItem.item_version == flag.PRODUCTVERSION){
                                 
                               item.qty = flag.sub_qty;
                               hasValue = true;
                           } 
                         })
                      if(!hasValue){
                        item.qty = 0;
                      }     

                  } else {
                        item.qty = 0; 
                  }
                
               
               })


                var select_detail;
                var abnormal_detail_backup = [],//不良原因備份
                labor_detail_backup,//多人產量登入備份
                production_inf_detail_backup;//生產資訊備份
                $rootScope.isRefreshCY = false; // 20230526 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                $rootScope.dispatch_filter = {};
                //20210330 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                var OutQtyOption = ''; //'1' = 該設備設定為「均分出站量」
               
                // 動態載入表單 内容动态截取
               var fragmentDataItems = JSON.parse(JSON.stringify(items));
               fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = fragmentDataItems.lst_ORM_EquipmentPeriodModel;
               var selectData = fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail.filter((item,$index)=>{
               // item.qty =  (item.capacity - item.used_capacity>0) ? (item.capacity - item.used_capacity): 0;  
                // item.qty = item.sub_qty;

                // item.suggest_detail.forEach(flag=>{
                //         if(plotItem.op_no == flag.OPNO &&plotItem.item_no == flag.PRODUCTNO&& plotItem.item_version == flag.PRODUCTVERSION){
                              
                //           item.sub_qty = flag.sub_qty;    
                //          }
                //      })
                 return  $index >= index;   
               })
    
               fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = selectData;
               var list = []; list.push(fragmentDataItems);
           
                //20210607 Add by Tim for#增加SQL實體分頁功能：記錄分頁資訊.
                var pageSetting = { PageNumber: 1, PageRow: 25, TotalPage: 1 };
                // 20221011 modify by Alan for#118808 : 重構開窗邏輯
                var openDialog = function () {
                    $mdDialog.dialog(
                        'module/moduleA/program/A08/A0801/A0801.html',
                        function (dialog) {
                            return {
                                css_url: 'module/moduleA/program/A08/A0801/A0801.css',
                                tmpLotNo:plot_no || '', // 20220810 add by zhuyuchao for#添加查询条件
                                tmpProductNo: '',
                                tmpProductName: '',
                                condition_item: {
                                   date_type:1,
                                   device_type:0 
                                },
                                dateIndex:index,
                                list:list,
                                qtyCopy:unDispatchItem.qty,
                                qty:unDispatchItem.qty,
                                machine_detail:machine_detail,
                                machineDetailCopy:machine_detail,
                                plotNumber:plotItem.plot_no,
                                detail: items,
                                mode: 'trackout',
                                parent: parent,
                                parentIndex:parentIndex,
                                select_detail: undefined,
                                tmpLabor_no: '',
                                op_plug_in: plotItem.op_plug_in, // 是否有爐批號 → 0(無) ; 1(有)
                                showFlag: false,
                                logFlag: false,
                                totalData:0,
                                page_setting: pageSetting, //20210607 Add by Tim for#增加SQL實體分頁功能：記錄分頁資訊.
                                init: function () {
                                    if (dialog.op_plug_in == '1' && dialog.heat_plot_no) {
                                        // 熱處理狀態所有生產批都會是打勾的，而且不能取消勾選。
                                        dialog.is_selectAll = true;
                                        // dialog.plotData.workstation_detail.forEach(function (item) {
                                        //     item.checked = true;
                                        // });
                                  }

                                   // 指定设备最终入参
                                   dialog.result = {
                                        lst_CDO_need_dispatch_equipment_detail:[

                                        ]
                                  };
                                  // 指定日期最终入参
                                  dialog.dateResult = {
                                        lst_CDO_need_dispatch_equipment_detail:[
                                               ...machine_detail   
                                        ]
                                        
                                 }
                                 
                                 dialog.detail.lst_CDO_need_dispatch_equipment_period_detail = dialog.detail.lst_ORM_EquipmentPeriodModel;
                                
                                  // 载入设备列表动态表头
                                  $rootScope.updateResult = function(item) {
                                        let list = generateResultHeader(item);
                                        if ($('.result').length != 0) {
                                                $('.result').replaceWith(list);
                                        }
                                      
                                        $compile(list)($rootScope);
                                }
                                function generateResultHeader(item) {
                                        let rows = generateResultRow(item);
                                        let start = `<div class="kmi-list column-selector">
                                                        <div class="kmi-list__header">
                                                        <div class="kmi-list__column require" style="flex:1;min-width:80px;"  ng-bind="'A05.equipment_view.equipment_no' | translate"></div>
                                                        <div class="kmi-list__column head-controls require" style="flex:1;min-width:80px;">
                                                                <div class="order" ng-hide="dispatch_filterSH.op_no">
                                                                <label ng-bind="'A03.list.column4' | translate"></label>
                                                                </div>
                                                        </div>
                                                        `;
                                        let end = `     </div>
                                                        <div class="kmi-list__row-content">
                                                            ${rows}
                                                        </div>
                                                    </div>`;
                                        let columns = '';
                                        let total = `<div class="kmi-list__column" style="flex:1;" ng-bind="'A08.total' | translate"></div>`;
                                        item.forEach(field => 
                                                columns += `<div class="kmi-list__column" style="flex: 0 0 120px;" ng-bind="'${ field.work_date.split('-')[1] }' + '/' + '${ field.work_date.split('-')[2] }'"></div>`);
                                        let list = $(start + columns  + total  + end);
                        
                                        return list
                                    }
                                   
                                    var MainPageEvent = function () {
                                        return {
                                            headerTitle:
                                                $filter("translate")("QT07.prefix") +
                                                "｜" +
                                                $filter("translate")("QT07.title"),
                                            model_name: '',
                                            TDList: [],
                                            condition: [],
                                            DTList: [],
                                            columnList: [],
                                            list:list,
                                            listCopy:list,
                                            extendData: {
                                                columnList: [],
                                                data: []
                                            },
                                            resultPageConfig: {
                                                page: 0,
                                                page_count: 25,
                                            },
                                            extendPageConfig: {
                                                page: 0,
                                                page_count: 25,
                                            } ,
                                            init() {

                                            },
                                            input_check_out_qty($event, data, $index) {
                                                dialog.input_check_out_qty($event, data, $index);
                                            }                      
                                          
                                        };
                                    };
                                $rootScope.main_event = MainPageEvent();
                                function generateResultRow(item) {
                                        var row = '';
                                        var columns = ``
                                        var start = ` <div class="kmi-list__row" ng-repeat="data in main_event.list" >               
                                        <div class="kmi-list__column column-border" style="flex:1;min-width:80px;font-size: 14px;" ng-bind=" '${ dialog.detail.machine_no }'"></div>                     
                                        <div class="kmi-list__column column-border" style="flex:1;min-width:80px;" ng-bind="'${ dialog.detail.machine_name }'"></div> 
                                        <div class="kmi-list__column column-input column-border" style="flex:1;z-index:1;position: relative;" ng-repeat="flag in data.lst_CDO_need_dispatch_equipment_period_detail">
                                          <input type="text" ng-click="main_event.input_check_out_qty($event,flag);" ng-value="flag.qty" readonly="readonly">
                                       </div>                      
                                      `;
                                        var end = `<div class="kmi-list__column column-input column-border" id="totalData" ng-bind="'${ dialog.totalData }'" style="flex:1;z-index:1;position: relative;">                             
                                         </div> </div>`;
                                        row = start + columns + end;
                        
                                        return row;
                                }
                                  setTimeout(() => {

                                     if ($rootScope.main_event.list.length) {
                                        $rootScope.updateResult($rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail);
                                     }
                                  });
                                 
                                  dialog.deviceDispatchVolume = JSON.parse(JSON.stringify(dialog.detail.lst_CDO_need_dispatch_equipment_period_detail));
                                   // 初始化指定日期的派工
                                 
                                   var fragmentData = [];
                                   dialog.dateList = JSON.parse(JSON.stringify(dialog.machine_detail));
                                   for(var i = dialog.parentIndex;i < dialog.dateList.length;i++){

                                       dialog.dateList[i].lst_ORM_EquipmentPeriodModel =  dialog.dateList[i].lst_ORM_EquipmentPeriodModel.filter((item,index)=>{
                                         item.suggest_detail.forEach(flag=>{
                                              if(plotItem.op_no == flag.OPNO &&plotItem.item_no == flag.PRODUCTNO&& plotItem.item_version == flag.PRODUCTVERSION){                                                           
                                                  item.qty = flag.sub_qty;    
                                                 }
                                               })
                                          return index == dialog.dateIndex;  
                                        })
                                      var obj=dialog.dateList[i];
                                      fragmentData.push(obj);
                                        
                                   }
                                  
                                   dialog.machine_detail =  fragmentData;
                                   dialog.machine_detailCopyData = JSON.parse(JSON.stringify(fragmentData));
                                   var total = {
                                        machine_no:"合计",
                                        lst_ORM_EquipmentPeriodModel:[{ 
                                                qty:0
                                               
                                        }]
                                   }
                                   dialog.machine_detail.push(total);
                                   dialog.machine_detailCopyData.push(total);
                                   dialog.AssignmentNumber(dialog.condition_item,flag=1);
                                  // dialog.result.lst_CDO_need_dispatch_equipment_detail.push($rootScope.main_event.list[0]);
                                  // 建議派工量 如果派工量小于第一天的剩余产量
                                                       
                                  var  reworkMethod='';
                                    // 20201215 add FOR #83685
                                    if (reworkMethod != "0") {
                                        dialog.showFlag = true;
                                    }
                                   
                                }, 
                                // 清除派工
                                dispatchClear: function (){
                                     for ( var x=0;x <dialog.machine_detail.length;x++){
                                         dialog.machine_detail[x].lst_ORM_EquipmentPeriodModel[0].qty = 0;
                                      }
                                   
                                     for ( var x=0;x<$rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.length;x++){
                                             $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[x].qty = 0;
                                      }
                                      dialog.totalData = 0;
                                      $("#totalData").html(0);
                                      
                                },
                                // 派工方式
                                suggestDispatch:function(param){
                                    var deviceListCopy = JSON.parse(JSON.stringify($rootScope.main_event.listCopy)); // 
                                    if(dialog.condition_item.device_type == 0){                                            
                                         $rootScope.main_event.list = deviceListCopy;
                                    } 
                                    // 指定设备                                                                  
                                   if(dialog.condition_item.device_type == 0) {                                    
                                           // 建议派工量
                                           dialog.qty = dialog.qtyCopy;
                                           dialog.totalData = 0;
                                           var q = 0;

                                           for(var i = 0;i < $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.length;i++){  
        
                                              if ( dialog.qty < $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[i].qty){
                                                q = i + 1;
                                                 $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[i].qty  = dialog.qty;
                                                 break; 

                                              } else { 
                                                  q++;
                                                  dialog.qty -= $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[i].qty;                      
                                              }
                                           };
                                                    
                                             for (q;q < $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.length;q++){
                                                 $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[q].qty = 0;
                                             }

                                             $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.forEach(item=>{
                                                 dialog.totalData +=  item.qty;
                                             })                                                                                                
                                               
                                           // 指定派工量
                                        } else {   // 指定日期
                                                                               
                                              dialog.qty = dialog.qtyCopy; 
                                              if(param == 1)  { 
                                                   dialog.machine_detail  = JSON.parse(JSON.stringify(dialog.machine_detailCopyData));
                                              }      
                                              var j = 0;
                                              // 派工量 从开始日期全量分配，（剩余的日期派工量默认为0）
                                              for( var i = 0;i < dialog.machine_detail.length-1;i++ ) {  

                                                   if(dialog.machine_detail[i].lst_ORM_EquipmentPeriodModel) {
                                                        
                                                      if (dialog.qty < dialog.machine_detail[i].lst_ORM_EquipmentPeriodModel[0].qty) {

                                                          j = i+1;
                                                          dialog.machine_detail[i].lst_ORM_EquipmentPeriodModel[0].qty = dialog.qty;
                                                          break; 

                                                      } else {
                                                          j++
                                                          dialog.qty -= dialog.machine_detail[i].lst_ORM_EquipmentPeriodModel[0].qty;
                                                      }
                                                  }
                                                  
                                             };
                                            // 派工量在前面的日期已经分配完, 剩余日期指定为0   
                                            if(dialog.machine_detail.length > 2) {
                                               for ( j;j < dialog.machine_detail.length-1;j++ ){
                                                  dialog.machine_detail[j].lst_ORM_EquipmentPeriodModel[0].qty = 0;
                                                }
                                            }     
                                            // 合计求和        
                                            var totalQty = 0;
                                            for ( var s = 0;s <(dialog.machine_detail.length)-1;s++){
                                                totalQty  +=  dialog.machine_detail[s].lst_ORM_EquipmentPeriodModel[0].qty; 
                                            }
                                            dialog.machine_detail[dialog.machine_detail.length-1].lst_ORM_EquipmentPeriodModel[0].qty = totalQty;
                                      }
                                   
                                  },
                                  appointDispatch() {   // 指定派工量设置派工量为0                                     
                                    if(dialog.condition_item.device_type == 0) { 
                                        for ( var g = 0; g < $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.length;g++) {
                                            $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail[g].qty = 0;
                                         }     
                                      } else {
                                        
                                        for ( var m = 0;m < dialog.machine_detail.length;m ++) {
                                           if( dialog.machine_detail[m].lst_ORM_EquipmentPeriodModel) {
                                                   dialog.machine_detail[m].lst_ORM_EquipmentPeriodModel[0].qty = 0;
                                           }                                              
                                        }
                                    }                                 

                                },                                           
                                changeAssignment(param,flag) {  
                                   // 指派方式                                                                    
                                   param.device_type = flag;
                                   if(param.date_type == 2) {

                                      $("#totalData").html(0);

                                      dialog.appointDispatch(flag); 

                                   } else {

                                     dialog.suggestDispatch(flag);
                                   }                                
                                },
                                // 指派数量
                                AssignmentNumber(param,flag) {                                 
                                  param.date_type = flag;
                                  if(param.date_type == 2) {
                                        $("#totalData").html(0);
                                      dialog.appointDispatch();
                                  } else {
                                    dialog.suggestDispatch(flag);
                                    $timeout(function () { //^_^ADD BY H-15016  20230614 FOR M#132192: 多日派工功能优化（设备显示、派工校验）
                                        $("#totalData").html(dialog.totalData);
                                    }, 200)
                                  }
                                                                 
                                },
                                close: function () {
                                    this.hide();
                                    // 20230526 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                    if ($rootScope.isRefreshCY && feedback) //产能存在异动，返回派工界面后需要刷新
                                        feedback();
                                },
                                filterSearch(e){
                                  var keycode = window.event?e.keyCode:e.which; 
                                  if(keycode==13){ 
                                     dialog.update();
                                  }
                                },// 20221123 modify by shiwl 清空放大镜的输入筛选
                                clearFilter(){
                                  dialog.op_no = '';
                                  dialog.item_spec = '';
                                  dialog.op_name = '';
                                  dialog.update();
                                },
                                paramtershow: function () {
                                    if (config.cache.sys_parameter['UCBModule'] == '1') {
                                        return true;
                                    }
                                    else
                                        return false;
                                },
                                back: backToTrackOut,
                                selectAll: function () {
                                    if (dialog.op_plug_in == '1' && dialog.heat_plot_no) {
                                        // 熱處理狀態不能取消勾選！
                                        $rootScope.showAlert($filter('translate')('B0219.msg.column10'));
                                    }
                                    else {
                                        dialog.is_selectAll = !dialog.is_selectAll;
                                        dialog.plotData.workstation_detail.forEach(function (item) {
                                            item.checked = dialog.is_selectAll;
                                        });
                                    };

                                },
                                itemCheck: function (item) {
                                    if (dialog.op_plug_in == '1' && dialog.heat_plot_no) {
                                        // 熱處理狀態不能取消勾選！
                                        $rootScope.showAlert($filter('translate')('B0219.msg.column10'));
                                    }
                                    else {
                                        item.checked = !item.checked
                                        if (!item.checked) {
                                            dialog.is_selectAll = false;
                                        }
                                    };
                                },
                                // 20201214 modify by 外包 for M#83685: 重工批重复扣料多模式选择。
                                itemChange: function (item) {
                                    if (item.rework_material_type == "0" || dialog.autoReworkMaterialProcess == "2") {
                                        return;
                                    }
                                    item.plusChecked = !item.plusChecked
                                },
                                // 20201214 modify by 外包 for M#83685: 重工批重复扣料多模式选择。
                                showLog: function (data) {
                                    data.logFlag = true;
                                },
                                // 20201214 modify by 外包 for M#83685: 重工批重复扣料多模式选择。
                                leaveLog: function (data) {
                                    data.logFlag = false;
                                },
                                // 20230525 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                beforeConfirmCheck(callback) {
                                    var query_condition_info = [
                                        { column_name: 'EquipmentNo', query_mode: '0', value: 'N/A', merge_condition_model: 'AND' },
                                        { column_name: 'LotNo', query_mode: '0', value: dialog.tmpLotNo, merge_condition_model: 'AND' },
                                        { column_name: 'OpNo', query_mode: '0', value: unDispatchItem.op_no, merge_condition_model: 'AND' }
                                    ];

                                    $MMWService.pageNumberInfoGet({
                                        page_mode: 'getCurUndispatchQty',
                                        query_condition_info: query_condition_info
                                    }, function (itemList) {
                                        var cur_qty = 0;
                                        if (itemList && itemList.length > 0) {
                                            cur_qty = (+itemList[0].curqty);
                                        }
                                        if ((+cur_qty) != (+dialog.qtyCopy)) {
                                            $rootScope.isRefreshCY = true;
                                            $rootScope.showCheck($filter('translate')('A08.showAlert.column01', { plot_no: dialog.tmpLotNo }), function (check_dialog) {
                                                check_dialog.hide();
                                                dialog.qtyCopy = (+cur_qty);

                                                $MMWService.sendToServer({
                                                    uri: "ServicesSTD.Module_WIP.dispatch_area_info_new_get",
                                                    content: {
                                                        return_type: '0020',
                                                        area_no: unDispatchItem.area_no,
                                                        lst_opno: lst_opno,
                                                        work_start_date: dialog.detail.lst_ORM_EquipmentPeriodModel[0].work_date,
                                                        work_end_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.detail.lst_ORM_EquipmentPeriodModel.length - 1].work_date,
                                                        machine_statistics_condition: {
                                                            machine_no: (dialog.condition_item.device_type == 1) ? '' : dialog.detail.machine_no,
                                                            is_capacity: true
                                                        }
                                                    },
                                                    success: function (data) {
                                                        if (data == null || data.machine_statistcs_list.length == 0) {
                                                            $rootScope.showAlert($filter('translate')('common.msg.no_data') + '<br>');
                                                        } else {
                                                            $rootScope.isRefreshCY = true;
                                                            if (dialog.condition_item.device_type == 1) { // 指定日期
                                                                var fragmentData = [];
                                                                dialog.dateList = JSON.parse(JSON.stringify(data.machine_statistcs_list));
                                                                for (var i = dialog.parentIndex; i < dialog.dateList.length; i++) {
                                                                    dialog.dateList[i].lst_ORM_EquipmentPeriodModel = dialog.dateList[i].lst_ORM_EquipmentPeriodModel.filter((item, index) => {
                                                                        item.suggest_detail.forEach(flag => {
                                                                            if (plotItem.op_no == flag.OPNO && plotItem.item_no == flag.PRODUCTNO && plotItem.item_version == flag.PRODUCTVERSION) {
                                                                                item.qty = flag.sub_qty;
                                                                            }
                                                                        })
                                                                        return index == dialog.dateIndex;
                                                                    })
                                                                    var obj = dialog.dateList[i];
                                                                    fragmentData.push(obj);
                                                                }
                                                                dialog.machine_detail = fragmentData;
                                                                dialog.machine_detailCopyData = JSON.parse(JSON.stringify(fragmentData));
                                                                var total = {
                                                                    machine_no: "合计",
                                                                    lst_ORM_EquipmentPeriodModel: [{
                                                                        qty: 0
                                                                    }]
                                                                }
                                                                dialog.machine_detail.push(total);
                                                                dialog.machine_detailCopyData.push(total);
                                                            } else { // 指定设备
                                                                items = data.machine_statistcs_list[0];
                                                                dialog.machine_detail.forEach(item => {
                                                                    if (item.machine_no == items.machine_no) {
                                                                        item = items;
                                                                    }
                                                                });
                                                                hasValue = false; // 匹配到建議派工量
                                                                items.lst_ORM_EquipmentPeriodModel.forEach(item => {
                                                                    if (item.suggest_detail.length > 0) {
                                                                        item.suggest_detail.forEach(flag => {
                                                                            if (plotItem.op_no == flag.OPNO && plotItem.item_no == flag.PRODUCTNO && plotItem.item_version == flag.PRODUCTVERSION) {
                                                                                item.qty = flag.sub_qty;
                                                                                hasValue = true;
                                                                            }
                                                                        })
                                                                        if (!hasValue) {
                                                                            item.qty = 0;
                                                                        }
                                                                    } else {
                                                                        item.qty = 0;
                                                                    }
                                                                })
                                                                // 動態載入表單 内容动态截取
                                                                var fragmentDataItems = JSON.parse(JSON.stringify(items));
                                                                fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = fragmentDataItems.lst_ORM_EquipmentPeriodModel;
                                                                var selectData = fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail.filter((item, $index) => {
                                                                    return $index >= index;
                                                                })
                                                                fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = selectData;
                                                                list = []; list.push(fragmentDataItems);
                                                                $rootScope.main_event.list = list;
                                                                $rootScope.main_event.listCopy = list;
                                                            }
                                                            dialog.suggestDispatch(1); //建议派工量
                                                            $timeout(function () { //^_^ADD BY H-15016  20230614 FOR M#132192: 多日派工功能优化（设备显示、派工校验）
                                                                $("#totalData").html(dialog.totalData);
                                                            }, 200);
                                                        }
                                                    }
                                                });
                                                if (dialog.condition_item.date_type == 2) {
                                                    $("#totalData").html(0);
                                                    dialog.appointDispatch(); //指定派工量
                                                } else {
                                                    dialog.suggestDispatch(1); //建议派工量
                                                    $timeout(function () { //^_^ADD BY H-15016  20230614 FOR M#132192: 多日派工功能优化（设备显示、派工校验）
                                                        $("#totalData").html(dialog.totalData);
                                                    }, 200);
                                                }
                                            });
                                        } else {
                                            if (callback)
                                                callback();
                                        }
                                    });
                                },
                                // 20201214 modify by 外包 for M#83685: 重工批重复扣料多模式选择。
                                confirmCheck() {  
                                    dialog.beforeConfirmCheck(function () { // 20230525 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                        // 本次派工数量不可大于派工数量 0指定设备
                                        var isConfirm =false;
                                        var plot_time= dialog.machine_detail[0].lst_ORM_EquipmentPeriodModel[0].work_date; 
                                        var content = {};
                                        if(dialog.condition_item.device_type == 1){  // 指定日期入参
                                                var totalQty = dialog.machine_detail[dialog.machine_detail.length-1].lst_ORM_EquipmentPeriodModel[0].qty;
                                                console.log( dialog.machine_detail[dialog.machine_detail.length-1].lst_ORM_EquipmentPeriodModel[0].qty);
                                                
                                            if(totalQty > dialog.qtyCopy){
                                            
                                                $rootScope.showAlert($filter('translate')('A08.dispatching_quantity_cannot_be_greater_than_the_dispatching_quantity')); 
                                                return;
                                            } 
                                            dialog.machine_detail.forEach(item=>{
                                                item.lst_CDO_need_dispatch_equipment_period_detail= item.lst_ORM_EquipmentPeriodModel;
                                            })
                                            content = {
                                                lst_opno:lst_opno,
                                                isConfirm:isConfirm,
                                                area_no: unDispatchItem.area_no,
                                                plot_no: unDispatchItem.plot_no,
                                                mo_no: unDispatchItem.wo_no,
                                                qty: dialog.machine_detail[dialog.machine_detail.length-1].lst_ORM_EquipmentPeriodModel[0].qty,
                                                op_no: unDispatchItem.op_no,
                                                plugin: unDispatchItem.plugin,
                                                dispatch_type: dialog.condition_item.device_type,
                                                plot_time: plot_time,
                                                work_start_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                work_end_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                lst_CDO_need_dispatch_equipment_detail:dialog.machine_detail,
                                                plot_end_time:unDispatchItem.plot_end_time,
                                                plot_start_time:unDispatchItem.plot_start_time
                                                        
                                            }
                                        }else {   // 指定设备入参

                                        var totalDataQty =   $("#totalData").html();   
                                            if(totalDataQty > dialog.qtyCopy){
                                            
                                                $rootScope.showAlert($filter('translate')('A08.dispatching_quantity_cannot_be_greater_than_the_dispatching_quantity')); 
                                                return;
                                            } 
                                            
                                            content = {};
                                            dialog.result.isConfirm=isConfirm,
                                                dialog.result.isconfirmyd = (dialog.condition_item.date_type == 2) ? 0 : 1; // 20230526 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                                dialog.result.area_no = unDispatchItem.area_no;
                                                dialog.result.plot_no = unDispatchItem.plot_no;
                                                dialog.result.mo_no = unDispatchItem.wo_no;
                                                dialog.result.qty = dialog.totalData;
                                                dialog.result.op_no = unDispatchItem.op_no;
                                                dialog.result.plugin = unDispatchItem.plugin;
                                                dialog.result.dispatch_type = dialog.condition_item.device_type;
                                                dialog.result.plot_time =unDispatchItem.plot_time;
                                                dialog.result.work_end_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[list[0].lst_CDO_need_dispatch_equipment_period_detail.length-1].work_date; 
                                                dialog.result.work_start_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[0].work_date;
                                                dialog.result.machine_no = dialog.detail.machine_no;
                                                dialog.result.lst_CDO_need_dispatch_equipment_detail = $rootScope.main_event.list;
                                                dialog.result.lst_opno = lst_opno;
                                                dialog.result.plot_end_time = unDispatchItem.plot_end_time;
                                                dialog.result.plot_start_time = unDispatchItem.plot_start_time;
                                                content =  dialog.result;

                                        }
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_period_process',
                                            content:content,
                                            success: function (data, response) {
                                                    $rootScope.showToast($filter('translate')('A05.js.success'));
                                                dialog.hide();
                                                if(feedback)
                                                    feedback();
                                            },
                                            error: function (data, response) {
                                                if (data.Code == 1) {
                                                    // 建議派工
                                                    if (content.isconfirmyd == 1) {
                                                        $rootScope.showConfirm(data.Message, function (confirm_dialog) {
                                                            confirm_dialog.hide();
                                                            // 20230525 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                                            //重新计算当前日期范围内生产批的建议派工量
                                                            $MMWService.sendToServer({
                                                                uri: "ServicesSTD.Module_WIP.dispatch_area_info_new_get",
                                                                content: {
                                                                    return_type: '0020',
                                                                    area_no: unDispatchItem.area_no,
                                                                    lst_opno: lst_opno,
                                                                    work_start_date: dialog.detail.lst_ORM_EquipmentPeriodModel[0].work_date,
                                                                    work_end_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.detail.lst_ORM_EquipmentPeriodModel.length - 1].work_date,
                                                                    machine_statistics_condition: {
                                                                        machine_no: (dialog.condition_item.device_type == 1) ? '' : dialog.detail.machine_no,
                                                                        is_capacity: true
                                                                    }
                                                                },
                                                                success: function (data) {
                                                                    if (data == null || data.machine_statistcs_list.length == 0) {
                                                                        $rootScope.showAlert($filter('translate')('common.msg.no_data') + '<br>');
                                                                    } else {
                                                                        $rootScope.isRefreshCY = true;

                                                                        if (dialog.condition_item.device_type == 1) {  // 指定日期
                                                                            var fragmentData = [];
                                                                            dialog.dateList = JSON.parse(JSON.stringify(data.machine_statistcs_list));
                                                                            for (var i = dialog.parentIndex; i < dialog.dateList.length; i++) {

                                                                                dialog.dateList[i].lst_ORM_EquipmentPeriodModel = dialog.dateList[i].lst_ORM_EquipmentPeriodModel.filter((item, index) => {
                                                                                    item.suggest_detail.forEach(flag => {
                                                                                        if (plotItem.op_no == flag.OPNO && plotItem.item_no == flag.PRODUCTNO && plotItem.item_version == flag.PRODUCTVERSION) {
                                                                                            item.qty = flag.sub_qty;
                                                                                        }
                                                                                    })
                                                                                    return index == dialog.dateIndex;
                                                                                })
                                                                                var obj = dialog.dateList[i];
                                                                                fragmentData.push(obj);
                                                                            }

                                                                            dialog.machine_detail = fragmentData;
                                                                            dialog.machine_detailCopyData = JSON.parse(JSON.stringify(fragmentData));
                                                                            var total = {
                                                                                machine_no: "合计",
                                                                                lst_ORM_EquipmentPeriodModel: [{
                                                                                    qty: 0

                                                                                }]
                                                                            }
                                                                            dialog.machine_detail.push(total);
                                                                            dialog.machine_detailCopyData.push(total);
                                                                        } else {   // 指定设备
                                                                            items = data.machine_statistcs_list[0];
                                                                            dialog.machine_detail.forEach(item => {
                                                                                if (item.machine_no == items.machine_no) {
                                                                                    item = items;
                                                                                }
                                                                            });

                                                                            hasValue = false; // 匹配到建議派工量
                                                                            items.lst_ORM_EquipmentPeriodModel.forEach(item => {
                                                                                if (item.suggest_detail.length > 0) {
                                                                                    item.suggest_detail.forEach(flag => {
                                                                                        if (plotItem.op_no == flag.OPNO && plotItem.item_no == flag.PRODUCTNO && plotItem.item_version == flag.PRODUCTVERSION) {
                                                                                            item.qty = flag.sub_qty;
                                                                                            hasValue = true;
                                                                                        }
                                                                                    })
                                                                                    if (!hasValue) {
                                                                                        item.qty = 0;
                                                                                    }
                                                                                } else {
                                                                                    item.qty = 0;
                                                                                }
                                                                            })

                                                                            // 動態載入表單 内容动态截取
                                                                            var fragmentDataItems = JSON.parse(JSON.stringify(items));
                                                                            fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = fragmentDataItems.lst_ORM_EquipmentPeriodModel;
                                                                            var selectData = fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail.filter((item, $index) => {
                                                                                return $index >= index;
                                                                            })

                                                                            fragmentDataItems.lst_CDO_need_dispatch_equipment_period_detail = selectData;
                                                                            list = []; list.push(fragmentDataItems);
                                                                            $rootScope.main_event.list = list;
                                                                            $rootScope.main_event.listCopy = list;
                                                                        }

                                                                        dialog.suggestDispatch(1); //建议派工量
                                                                        $timeout(function () { //^_^ADD BY H-15016  20230614 FOR M#132192: 多日派工功能优化（设备显示、派工校验）
                                                                            $("#totalData").html(dialog.totalData);
                                                                        }, 200);
                                                                    }
                                                                }
                                                            });
                                                        }, function (cancel_dialog) { // 20230525 modify by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                                            cancel_dialog.hide();
                                                            isConfirm = true;//继续执行
                                                            var plot_time = dialog.machine_detail[0].lst_ORM_EquipmentPeriodModel[0].work_date;
                                                            var content = {};
                                                            // 指定日期
                                                            if (dialog.condition_item.device_type == 1) {
                                                                dialog.machine_detail.forEach(item => {
                                                                    item.lst_CDO_need_dispatch_equipment_period_detail = item.lst_ORM_EquipmentPeriodModel;
                                                                })
                                                                content = {
                                                                    lst_opno: lst_opno,
                                                                    isConfirm: isConfirm,
                                                                    isconfirmyd: 0, // 20230526 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                                                    area_no: unDispatchItem.area_no,
                                                                    plot_no: unDispatchItem.plot_no,
                                                                    mo_no: unDispatchItem.wo_no,
                                                                    qty: dialog.machine_detail[dialog.machine_detail.length - 1].lst_ORM_EquipmentPeriodModel[0].qty,
                                                                    op_no: unDispatchItem.op_no,
                                                                    plugin: unDispatchItem.plugin,
                                                                    dispatch_type: dialog.condition_item.device_type,
                                                                    plot_time: plot_time,
                                                                    work_start_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                                    work_end_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                                    lst_CDO_need_dispatch_equipment_detail: dialog.machine_detail,
                                                                    plot_end_time:unDispatchItem.plot_end_time,
                                                                    plot_start_time:unDispatchItem.plot_start_time
                                                                }

                                                            } else {
                                                                // 指定設備
                                                                content = {};
                                                                dialog.result.isConfirm = isConfirm;
                                                                dialog.result.isconfirmyd = 0; // 20230526 add by 15016 for M#132192: 多日派工功能优化（设备显示、派工校验）
                                                                dialog.result.area_no = unDispatchItem.area_no;
                                                                dialog.result.plot_no = unDispatchItem.plot_no;
                                                                dialog.result.mo_no = unDispatchItem.wo_no;
                                                                dialog.result.qty = dialog.totalData;
                                                                dialog.result.op_no = unDispatchItem.op_no;
                                                                dialog.result.plugin = unDispatchItem.plugin;
                                                                dialog.result.dispatch_type = dialog.condition_item.device_type;
                                                                dialog.result.plot_time = unDispatchItem.plot_time;
                                                                dialog.result.work_end_date = unDispatchItem.work_end_date;
                                                                dialog.result.work_end_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[list[0].lst_CDO_need_dispatch_equipment_period_detail.length - 1].work_date;
                                                                dialog.result.work_start_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[0].work_date;
                                                                dialog.result.lst_opno = lst_opno;
                                                                dialog.result.plot_end_time = unDispatchItem.plot_end_time;
                                                                dialog.result.plot_start_time = unDispatchItem.plot_start_time;
                                                                content = dialog.result;

                                                            }

                                                            $MMWService.sendToServer({
                                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_period_process',
                                                                content: content,
                                                                success: function (data, response) {
                                                                    $rootScope.showToast($filter('translate')('A05.js.success'));
                                                                    dialog.hide();
                                                                    if (feedback)
                                                                        feedback();
                                                                }
                                                            });
                                                        });
                                                    } else {
                                                        // 指定派工
                                                        $rootScope.showConfirm(data.Message, function (dialog1) {
                                                            dialog1.hide();
                                                            isConfirm = true;//继续执行
                                                            var plot_time = dialog.machine_detail[0].lst_ORM_EquipmentPeriodModel[0].work_date;
                                                            var content = {};
                                                            if (dialog.condition_item.device_type == 1) {
                                                                dialog.machine_detail.forEach(item => {
                                                                    item.lst_CDO_need_dispatch_equipment_period_detail = item.lst_ORM_EquipmentPeriodModel;
                                                                })
                                                                content = {
                                                                    lst_opno: lst_opno,
                                                                    isConfirm: isConfirm,
                                                                    area_no: unDispatchItem.area_no,
                                                                    plot_no: unDispatchItem.plot_no,
                                                                    mo_no: unDispatchItem.wo_no,
                                                                    qty: dialog.machine_detail[dialog.machine_detail.length - 1].lst_ORM_EquipmentPeriodModel[0].qty,
                                                                    op_no: unDispatchItem.op_no,
                                                                    plugin: unDispatchItem.plugin,
                                                                    dispatch_type: dialog.condition_item.device_type,
                                                                    plot_time: plot_time,
                                                                    work_start_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                                    work_end_date: dialog.detail.lst_ORM_EquipmentPeriodModel[dialog.dateIndex].work_date,
                                                                    lst_CDO_need_dispatch_equipment_detail: dialog.machine_detail,
                                                                    plot_end_time:unDispatchItem.plot_end_time,
                                                                    plot_start_time:unDispatchItem.plot_start_time
                                                                }

                                                            } else {
                                                                content = {};
                                                                dialog.result.isConfirm = isConfirm;
                                                                dialog.result.area_no = unDispatchItem.area_no;
                                                                dialog.result.plot_no = unDispatchItem.plot_no;
                                                                dialog.result.mo_no = unDispatchItem.wo_no;
                                                                dialog.result.qty = dialog.totalData;
                                                                dialog.result.op_no = unDispatchItem.op_no;
                                                                dialog.result.plugin = unDispatchItem.plugin;
                                                                dialog.result.dispatch_type = dialog.condition_item.device_type;
                                                                dialog.result.plot_time = unDispatchItem.plot_time;
                                                                dialog.result.work_end_date = unDispatchItem.work_end_date;
                                                                dialog.result.work_end_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[list[0].lst_CDO_need_dispatch_equipment_period_detail.length - 1].work_date;
                                                                dialog.result.work_start_date = list[0].lst_CDO_need_dispatch_equipment_period_detail[0].work_date;
                                                                dialog.result.lst_opno = lst_opno;
                                                                dialog.result.plot_end_time = unDispatchItem.plot_end_time;
                                                                dialog.result.plot_start_time = unDispatchItem.plot_start_time;
                                                                content = dialog.result;

                                                            }

                                                            $MMWService.sendToServer({
                                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_period_process',
                                                                content: content,
                                                                success: function (data, response) {
                                                                    $rootScope.showToast($filter('translate')('A05.js.success'));
                                                                    dialog.hide();
                                                                    if (feedback)
                                                                        feedback();
                                                                }
                                                            });

                                                        });
                                                    }
                                                } else {
                                                    $rootScope.showAlert(data.Message);
                                                }
                                            }
                                        });
                                    });
                                },
                                confirm: function () {
                                    if (dialog.isRequire) {
                                        $rootScope.showAlert($filter('translate')('B0219.msg.production_inf_require'), function () {
                                            dialog.productionInf_open();
                                        });
                                    } else {
                                        goodQtyCheck(dialog, function () {
                                            ProductionParametersCheckProcess(dialog);
                                        });
                                    }
                                },
                                selectItem: function (index, data) {
                                    dialog.select_detail = data;
                                    if (!dialog.select_detail.abnormal_detail) {
                                        dialog.select_detail.abnormal_detail = [];
                                    }
                                },
                                selectDateItem: function (index, data) {
                                        dialog.select_detail = data;
                                        if (!dialog.select_detail.abnormal_detail) {
                                            dialog.select_detail.abnormal_detail = [];
                                        }
                                    },
                                changeAppointDateTotal:function(){
                                    //  指定日期合计统计
                                    var total = 0;

                                    dialog.machine_detail.forEach(item=>{
                                        if(item.machine_no!='合计'){
                                                total += parseInt(item.lst_ORM_EquipmentPeriodModel[0].qty);

                                        }
                                    })
                                    dialog.machine_detail[dialog.machine_detail.length-1].lst_ORM_EquipmentPeriodModel[0].qty = total;
                                   
                                },
                                dateSetDispatchVolume:function(event, data, index){
                                       
                                        var target = event.currentTarget;                                
                                        dialog.selectItem(index, data);
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(
                                            function (num, calcDialog) {
                                                data.qty = num;
                                                data.lst_ORM_EquipmentPeriodModel[0].qty =num;
                                                dialog.changeAppointDateTotal();
                                                calcDialog.hide();
                                            
                                            },
                                            function (calcDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calcDialog.hide();
                                            },
                                            {
                                                defaultNum: data.final,
                                                decimal: true
                                            }
                                        );
                                },
                                //20210330 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                input_check_out_qty: function (event, data, index) { //如果有手動更改qty
                                    var target = event.currentTarget;                                
                                   // dialog.selectItem(index, data);
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(
                                        function (num, calcDialog) {

                                                calcDialog.hide();
                                              
                                                data.qty = num;
                                                dialog.countTotal();   
                                          //     if ((+num) == 0) {
                                         //         $rootScope.showAlert($filter('translate')('B0219.msg.check_out_qty_zero'));
                                         //     } else if ((+num) > (+data.check_out_qty_backup)) {
                                         //         $rootScope.showAlert($filter('translate')('B0219.msg.column1') + data.check_out_qty_backup);
                                         //     } else {
                                              
                                             
                                                // if ((+num > data.qty)) {
                                                //         data.qty = num;
                                                //         $rootScope.showAlert("当前输入超过剩余产能");    
    
                                                // }
                                                                                          
                                              
                                          //  }
                                        },
                                        function (calcDialog) {
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            defaultNum: data.check_out_qty,
                                            decimal: true
                                        }
                                    );
                                },
                                countTotal:function() {

                                        dialog.totalData = 0;                                     
                                        $rootScope.main_event.list[0].lst_CDO_need_dispatch_equipment_period_detail.forEach(item=>{
                                                if(item.qty) {
                                                         dialog.totalData += parseInt(item.qty);
                                                } 
                                               
                                        })
                                        $("#totalData").html( dialog.totalData);
                                },
                                tmpBadReason: '',
                                tmpdefect_qty: '',
                                //開啟不良原因畫面
                                badReason_open: function () {
                                    var content = {
                                        op_no: dialog.select_detail.op_no
                                    };
                                    $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.qc_reason_basis_info_get',
                                        content: content,
                                        success: function (data, response) {
                                            //備份
                                            // badReasonInfo_backup = dialog.select_detail.abnormal_detail.slice();
                                            dialog.badTypeList = genBadType(data.qc_reason_basis, dialog.select_detail.abnormal_detail);
                                            if (dialog.badTypeList.length > 0) {
                                                dialog.tmpBadType = dialog.badTypeList[0].reason_type;
                                            }
                                            dialog.mode = 'badReason';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpAbnormal_qty = '';

                                            if (typeof data.smt_reason_basis != 'undefined' && data.smt_reason_basis.length > 0) {
                                                dialog.select_detail.abnormal_detail.push({
                                                    plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                                                    abnormal_type_name: data.smt_reason_basis[0].reason_sub_type,
                                                    abnormal_no: data.smt_reason_basis[0].reason_no,
                                                    abnormal_name: data.smt_reason_basis[0].reason_name,
                                                    defect_qty: data.smt_reason_basis[0].qty
                                                })

                                                dialog.mode = 'badReason';
                                                dialog.tmpBadReason = {};
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                                dialog.tmpdefect_qty = '';
                                                //備份當時的不明原因列�?
                                            }
                                            abnormal_detail_backup = dialog.select_detail.abnormal_detail.slice();
                                            $timeout(function () {
                                                if (document.activeElement.tagName != 'INPUT') {
                                                    document.querySelector(".searching-bad").focus();
                                                }
                                            });
                                        }
                                    });
                                },
                                add_BadReason_selected: function (item) {//增加不良原因到右側已選欄位
                                    item.chosen = 'Y';
                                    dialog.select_detail.abnormal_detail.push({
                                        reason_type: item.reason_type,
                                        reason_key: item.key,
                                        abnormal_type_name: item.reason_sub_type,
                                        abnormal_no: item.reason_no,
                                        abnormal_name: item.reason_name,
                                        defect_qty: 0
                                    })
                                },
                                delete_BadReason_selected: function (item) {//删除右側已選擇的不良原因
                                    dialog.select_detail.abnormal_detail.splice(dialog.select_detail.abnormal_detail.indexOf(item), 1);
                                    var _type_temp = $filter('filter')(dialog.badTypeList, { reason_type: item.reason_type }, true);
                                    var _temp = $filter('filter')(_type_temp[0].badReason_list, { reason_no: item.abnormal_no }, true);
                                    if (_temp.length > 0)
                                        _temp[0].chosen = undefined;
                                },
                                clickTypeItem: function (item) {//不良原因手風琴
                                    dialog.tmpBadType = item.reason_type;
                                },
                                //QRCode輸入
                                qrcode_plot_no: function () {
                                    $rootScope.OpenScanner({
                                        after: function (result) {
                                            var _item = BadReasonPick(dialog.badTypeList, result.text);
                                            if (!_item) {
                                                $rootScope.showAlert($filter('translate')('B0206.msg.cont_find_reason') + dialog.tmpBadTypeName);
                                                dialog.tmpBadTypeName = '';
                                            } else if (_item.chosen == 'Y') {
                                                $rootScope.showAlert($filter('translate')('B0206.msg.reason_already_exist') + dialog.tmpBadTypeName);
                                                dialog.tmpBadTypeName = '';
                                            } else {
                                                dialog.add_BadReason_selected(_item);
                                            }
                                        },
                                        exception: function () {
                                            //目前裝置無法使用相機
                                            $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                        },
                                        orientation: 'landscape'
                                    });
                                },
                                bd_scan: function (event) {
                                    if (event.keyCode == 13) {
                                        var _item = BadReasonPick(dialog.badTypeList, dialog.tmpBadTypeName);
                                        if (!_item) {
                                            $rootScope.showAlert($filter('translate')('B0206.msg.cont_find_reason') + dialog.tmpBadTypeName);
                                            dialog.tmpBadTypeName = '';
                                        } else if (_item.chosen == 'Y') {
                                            $rootScope.showAlert($filter('translate')('B0206.msg.reason_already_exist') + dialog.tmpBadTypeName);
                                            dialog.tmpBadTypeName = '';
                                        } else {
                                            dialog.tmpBadTypeName = '';
                                            dialog.add_BadReason_selected(_item);
                                        }
                                    }
                                },
                                badType_loadList: function () {
                                    $rootScope.showSelect({
                                        label: 'reason_sub_type',
                                        code: 'reason_type',
                                        selectCode: dialog.tmpBadType,
                                        list: dialog.badTypeList,
                                        confirm: function (item, radioDialog) {
                                            radioDialog.hide();
                                            dialog.tmpBadType = item.reason_type;
                                            dialog.tmpBadTypeName = item.reason_sub_type;
                                        }
                                    });
                                },
                                //不良原因列表
                                badReason_loadList: function () {
                                    if (dialog.tmpBadType != '') {
                                        $rootScope.showQueryList({
                                            key: 'reason_no',
                                            title: $filter('translate')('common.queryList.badReason_select'),
                                            header: [
                                                { label: $filter('translate')('common.queryList.reason_c'), code: 'reason_no' },
                                                { label: $filter('translate')('common.queryList.reason_n'), code: 'reason_name' }
                                            ],
                                            query: function (conditions, feedback) {
                                                feedback($filter('filter')(dialog.badCodeList, { reason_type: dialog.tmpBadType }));
                                            },
                                            confirm: function (selectItem, radioDialog) {
                                                radioDialog.hide();
                                                dialog.tmpBadReason = selectItem;
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0206.msg.bad_type_empty'));
                                    }
                                },
                                bd_scan: function (event) {
                                    if (event.keyCode == 13) {
                                        var _item = BadReasonPick(dialog.badTypeList, dialog.tmpBadTypeName);
                                        if (!_item) {
                                            $rootScope.showAlert($filter('translate')('B0206.msg.cont_find_reason') + dialog.tmpBadTypeName);
                                            dialog.tmpBadTypeName = '';
                                        } else if (_item.chosen == 'Y') {
                                            $rootScope.showAlert($filter('translate')('B0206.msg.reason_already_exist') + dialog.tmpBadTypeName);
                                            dialog.tmpBadTypeName = '';
                                        } else {
                                            dialog.tmpBadTypeName = '';
                                            dialog.add_BadReason_selected(_item);
                                        }
                                    }
                                },
                                AbnormalQtyAdjust: function (event, item) {//調整數量
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function (num, abCalcDialog) {
                                        angular.element(target).removeClass('is-focus');
                                        item.defect_qty = (+num);
                                        document.querySelector(".searching-bad").focus();//將焦點移回刷不良原因的條碼欄位。
                                        abCalcDialog.hide();
                                    },
                                        function (abCalcDialog) {
                                            angular.element(target).removeClass('is-focus');
                                            abCalcDialog.hide();
                                        },
                                        {
                                            defaultNum: item.defect_qty,
                                            decimal: false
                                        });
                                },
                                badReason_add: function () {
                                    if (!dialog.tmpBadReason.reason_no) {
                                        $rootScope.showAlert($filter('translate')('B0219.msg.column3'), function () {
                                            dialog.tmpBadType = '';
                                            dialog.tmpBadTypeName = '';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpdefect_qty = '';
                                        });
                                    } else {
                                        if (dialog.tmpdefect_qty > 0) {
                                            dialog.select_detail.abnormal_detail.push({
                                                plot_no: dialog.select_detail.plot_no,
                                                abnormal_type: dialog.tmpBadReason.reason_type,
                                                abnormal_type_name: dialog.tmpBadReason.reason_sub_type,
                                                abnormal_no: dialog.tmpBadReason.reason_no,
                                                abnormal_name: dialog.tmpBadReason.reason_name,
                                                defect_qty: dialog.tmpdefect_qty,
                                            });
                                            dialog.tmpBadType = '';
                                            dialog.tmpBadTypeName = '';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpdefect_qty = '';
                                        } else {
                                            $rootScope.showAlert($filter('translate')('B0219.msg.column4'), function () {
                                                dialog.tmpdefect_qty = '';
                                            });
                                        }
                                    }
                                },
                                badReason_remove: function (item) {
                                    dialog.select_detail.abnormal_detail.splice(dialog.select_detail.abnormal_detail.indexOf(item), 1);
                                },
                                badReason_confirm: function () {
                                    //檢核不良原因總數不可超過數量
                                    if (dialog.select_detail.abnormal_detail.length != 0) {
                                        var total_defect_qty = 0;
                                        var total_surplus_qty = 0;//多餘�?
                                        var total_lack_qty = 0;//短少�?
                                        var _msg = '';
                                        dialog.select_detail.abnormal_detail.forEach(function (badReason) {
                                            if (badReason.defect_qty == 0) {
                                                _msg = $filter('translate')('B0206.msg.badreason_qty_zero');
                                            } else {
                                                if (badReason.reason_type == '11') {
                                                    total_surplus_qty = $calculater.decimalAdd((+total_surplus_qty), (+badReason.defect_qty));
                                                } else if (badReason.reason_type == '12') {
                                                    total_lack_qty = $calculater.decimalAdd((+total_lack_qty), (+badReason.defect_qty));
                                                } else {
                                                    total_defect_qty = $calculater.decimalAdd((+total_defect_qty), (+badReason.defect_qty));
                                                }
                                            }
                                        });

                                        if (_msg != '') {
                                            $rootScope.showAlert(_msg);
                                            return;
                                        }

                                        if ((total_surplus_qty + (+dialog.select_detail.check_out_qty)) < (total_defect_qty + total_lack_qty)) {
                                            $rootScope.showAlert($filter('translate')('B0219.msg.column5') + dialog.select_detail.check_out_qty);
                                        } else {
                                            dialog.select_detail.total_defect_qty = total_defect_qty;
                                            dialog.select_detail.total_surplus_qty = total_surplus_qty;
                                            dialog.select_detail.total_lack_qty = total_lack_qty;
                                            //良品�?= 『出站數量�?- 『不良品�?- 『短少�?+ 『多餘�?
                                            dialog.select_detail.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.select_detail.check_out_qty), (+dialog.select_detail.total_surplus_qty)), (+dialog.select_detail.total_defect_qty)), (+dialog.select_detail.total_lack_qty));
                                            dialog.mode = 'trackout';

                                            dialog.tmpBadType = '';
                                            dialog.tmpBadTypeName = '';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpdefect_qty = '';
                                        }
                                    } else {
                                        dialog.select_detail.total_defect_qty = 0;
                                        dialog.select_detail.total_surplus_qty = 0;
                                        dialog.select_detail.total_lack_qty = 0;
                                        dialog.select_detail.good_qty = (+dialog.select_detail.check_out_qty);
                                        dialog.mode = 'trackout';

                                        dialog.tmpBadType = '';
                                        dialog.tmpBadTypeName = '';
                                        dialog.tmpBadReason = {};
                                        dialog.tmpdefect_qty = '';
                                        //$rootScope.showAlert("請輸入不良原�?);
                                    }
                                },
                                badReason_cancel: backToTrackOut,
                                //開啟多人產量登入
                                multiple_open: function () {
                                    dialog.mode = 'multiple';
                                    labor_detail_backup = angular.merge([], dialog.select_detail.labor_detail);
                                    //20210413 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                    dialog.setLaborCheckOutQTY(dialog.select_detail); //人員出站數量設定
                                },
                                addMultipleLabor: function (labor_no, labor_name) {
                                    var labor_detail = dialog.select_detail.labor_detail;
                                    var isExist = false;
                                    for (var i = 0; i < labor_detail.length; i++) {
                                        if (labor_detail[i].labor_no == labor_no) {
                                            isExist = true;
                                            break;
                                        }
                                    }
                                    if (!isExist) {
                                        labor_detail.push({ labor_no: labor_no, labor_name: labor_name, qty: dialog.select_detail.check_out_qty, labor_time: 0 });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0206.msg.labor_no_exist', { labor_no: labor_no })); //人員已存�?
                                    }
                                    dialog.tmpLabor_no = '';
                                },
                                deleteMultipleLabor: function (item) {
                                    $rootScope.showConfirm($filter('translate')('B0206.msg.is_delete_multiple_labor', { labor_name: item.labor_name }),
                                        function (confirmDialog) {
                                            confirmDialog.hide();
                                            var index = dialog.select_detail.labor_detail.indexOf(item);
                                            dialog.select_detail.labor_detail.splice(index, 1);
                                        }
                                    );
                                },
                                searchLabor: function (event) {
                                    if (!event || event.keyCode == 13) {
                                        if (dialog.tmpLabor_no != '') {
                                            var content = {
                                                machine_no: "machine_no",
                                                employee_no: dialog.tmpLabor_no,
                                                report_datetime: new Date(),
                                                return_type: '10'
                                            };

                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_SYS.user_information_get',
                                                content: content,
                                                success: function (data) {
                                                    dialog.addMultipleLabor(data.employee_no, data.employee_name);
                                                },
                                                error: function (data) {
                                                    $rootScope.showAlert(data.Message, function () {
                                                        document.getElementById('tmpLabor_no').focus();
                                                    });
                                                }
                                            });
                                        } else {
                                            $rootScope.showAlert($filter('translate')('B0206.msg.input_labor_empty'), function () {
                                                document.getElementById('tmpLabor_no').focus();
                                            });
                                        }
                                    }
                                },
                                multipleCheck: function () {
                                    var msg = '';
                                    var labor_detail = dialog.select_detail.labor_detail;
                                    if (labor_detail.length == 0) {
                                        msg = $filter('translate')('B0206.msg.labor_detail_empty'); //人員明細不可為空
                                    } else {
                                        for (var i = 0; i < labor_detail.length; i++) {
                                            if (labor_detail[i].labor_time == 0 && labor_detail[i].qty == 0) {
                                                msg = $filter('translate')('B0206.msg.qty_and_labor_time_is_empty'); //數量與人時不可同時為0�?
                                                break;
                                            }
                                        }
                                    }
                                    //20210413 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                    if (OutQtyOption == '1') { //有設定均分出站量才檢查加總是否超過最大出站量
                                        var sum = 0;
                                        labor_detail.forEach(function (item) {
                                            if (item.qty)
                                                sum += parseInt(item.qty, 10);
                                        });
                                        if (sum > dialog.select_detail.check_out_qty_backup) {
                                            msg = $filter('translate')('B0219.msg.column6') + dialog.select_detail.check_out_qty_backup; //請勿超過出站總數
                                        }
                                    }
                                    return msg;
                                },
                                multiple_confirm: function () {
                                    var msg = dialog.multipleCheck();
                                    if (msg == '') {
                                        //計算總人�?
                                        dialog.select_detail.labor_hours = 0;
                                        dialog.select_detail.number_of_labor = 0;
                                        dialog.select_detail.labor_detail.forEach(function (labor) {
                                            dialog.select_detail.labor_hours = $calculater.decimalAdd(dialog.select_detail.labor_hours, labor.labor_time);
                                            dialog.select_detail.number_of_labor += 1;
                                        });
                                        dialog.mode = 'trackout';
                                        //20210413 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                        if (OutQtyOption == '1') { //有設定均分出站量才需要計算合計數 回出站畫面時修改總數
                                            var trackOutCount = 0;
                                            dialog.select_detail.labor_detail.forEach(function (item) {
                                                trackOutCount += parseInt(item.qty, 10);
                                            });
                                            //寫回出站畫面
                                            dialog.select_detail.check_out_qty = trackOutCount;
                                            //總數 – 不良品 – 短少 + 多餘 = 良品數量
                                            dialog.select_detail.good_qty = trackOutCount - dialog.select_detail.total_defect_qty
                                                - dialog.select_detail.total_lack_qty + dialog.select_detail.total_surplus_qty;
                                        }
                                    } else {
                                        $rootScope.showAlert(msg);
                                    }
                                },
                                multiple_input_labor_qty: function (event, labor) {
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(
                                        function (num, calcDialog) {
                                            //20210412 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                            if ((+num) > (+dialog.select_detail.check_out_qty_backup)) {
                                                $rootScope.showAlert($filter('translate')('B0219.msg.column6') + dialog.select_detail.check_out_qty_backup); //請勿超過出站總數
                                            } else {
                                                calcDialog.hide();
                                                angular.element(target).removeClass('is-focus');
                                                labor.qty = num;
                                            }
                                        },
                                        function (calcDialog) {
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            defaultNum: labor.qty,
                                            decimal: true
                                        }
                                    );
                                },
                                multiple_cancel: backToTrackOut,
                                //進入生產資訊收集
                                productionInf_open: function () {
                                    if (dialog.plotData.production_inf_detail && dialog.plotData.production_inf_detail.length > 0) {
                                        dialog.mode = 'production_inf';
                                        production_inf_detail_backup = angular.merge([], dialog.plotData.production_inf_detail);
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0219.msg.production_inf_detail_empty'));
                                    }
                                },
                                switchInit: function (item) {
                                    if (!item.productioninf_value) {
                                        item.productioninf_value = '0';
                                    }
                                },
                                switchClick: function (item) {
                                    if (item.productioninf_value == '0') {
                                        item.productioninf_value = '1';
                                    } else {
                                        item.productioninf_value = '0';
                                    }
                                },
                                productionInfConfirm: function () {
                                    var msg = '';
                                    if (dialog.plotData.production_inf_type == '2') {
                                        msg = productionInfValidate(dialog.plotData.production_inf_detail);
                                    }
                                    if (msg == '') {
                                        dialog.isRequire = false;
                                        dialog.mode = 'trackout';
                                    } else {
                                        dialog.isRequire = true;
                                        $rootScope.showAlert(msg);
                                    }
                                },
                                //20210413 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                                //人員出站數量設定
                                setLaborCheckOutQTY: function (workstation_detail) {
                                    if (OutQtyOption == '1') { //'1' = 該設備設定為「均分出站量」
                                        var trackOutQty = workstation_detailgood_qty; //待出站量 20210413 Modify by yuting for#109224:[sMES]批次出站短少，人時數量錯誤[益睿]
                                        var numberOfLabor = workstation_detail.number_of_labor; //人數
                                        var averageQty = Math.floor(trackOutQty / numberOfLabor); //平均數
                                        workstation_detail.labor_detail.forEach(function (labor, index) {
                                            if (index == numberOfLabor - 1) {
                                                labor.qty = trackOutQty;
                                            } else {
                                                labor.qty = averageQty;
                                                trackOutQty -= averageQty;
                                            }
                                        });    
                                    }else{ //預設 原邏輯
                                        workstation_detail.labor_detail.forEach(function(labor){ 
                                            labor.qty =labor.labor_qty;//20220523 modi by wangyq for M#112750 old:labor.labor workstation_detail.check_out_qty;
                                        });
                                    }
                                },
                                //20210607 Add by Tim for#增加SQL實體分頁功能：執行前端分頁的[上一頁]功能.
                                previousPage: function () {
                                    if (pageSetting.PageNumber - 1 <= 0) {
                                        pageSetting.PageNumber = 1;
                                    }
                                    else {
                                        pageSetting.PageNumber = pageSetting.PageNumber - 1;
                                        dialog.update();
                                    }
                                },
                                //20210607 Add by Tim for#增加SQL實體分頁功能：執行前端分頁的[下一頁]功能.
                                nextPage: function () {
                                    if (pageSetting.PageNumber + 1 > (pageSetting.TotalPage)) {
                                        pageSetting.PageNumber = pageSetting.TotalPage;
                                    }
                                    else {
                                        pageSetting.PageNumber = pageSetting.PageNumber + 1;
                                        dialog.update();
                                    }
                                },
                                searchPlotList: function (event) {
                                    if (!event || event.keyCode == 13) {
                                        dialog.update();
                                    }
                                },
                                // 20221011 modify by Alan for#118808 : 重構開窗邏輯資料更新部分邏輯
                                update: function() {
                                    // 20220810 add by zhuyuchao for#添加查询条件
                                    var param = {
                                        lot_no: dialog.tmpLotNo,
                                        product_no: dialog.tmpProductNo,
                                        product_name: dialog.tmpProductName,
                                        op_no_like:dialog.op_no_like,
                                        item_spec: dialog.item_spec,
                                        op_name: dialog.op_name
                                    }
                                    //20221021 modify wangzy for M#0120982: 批次进站翻页报错
                                  //  pageSetting.PageNumber = 1;
                                    // 20220905 add by maxueli 修改数据页面加载不出来的问题，改为初次加载
                                    GetPlotInfoData(true, param, function(info) {
                                        // 更新dialog
                                        dialog.isRequire = info.data.production_inf_type == '2';
                                        dialog.plotData = info.data;
                                        dialog.autoReworkMaterialProcess = info.reworkMethod;
                                        dialog.heat_plot_no = info.opPlugInDetail.heat_plot_no || '';
                                        dialog.init();
                                    });
                                }
                            };
                        }
                    );
                };

                //20220325 add by 翰鴻 for M#107697
                //人員計價 出站 總額計算 add by a991241234 for M# 70310
                function getPriceSum(plotInfo) {
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    if (price_check_1 && price_check_2) {
                        switch (plotInfo.price_type) {
                            //計件
                            case "0":
                                if (isNaN(parseFloat(plotInfo.qty)) == false)
                                    plotInfo.price_sum = parseFloat(plotInfo.qty) * parseFloat(plotInfo.price);
                                break;
                            //計時
                            case "1":
                                if (isNaN(parseFloat(plotInfo.labor_hours)) == false)
                                    plotInfo.price_sum = parseFloat(plotInfo.labor_hours) * parseFloat(plotInfo.price);
                                break;
                        }
                    }
                }
                //人員計價 多人量產 總額計算 add by a991241234 for M# 70310
                function getPriceSumByLabor(plotInfo) {
                    //console.log(plotInfo.workstation_detail[0].labor_detail);
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    var price_check_3 = plotInfo.labor_detail.length > 0;
                    if (price_check_1 && price_check_2 && price_check_3) {
                        switch (plotInfo.price_type) {
                            //計件
                            case "0":
                                var sum = 0;
                                for (var i in plotInfo.labor_detail) {
                                    var qty;
                                    if (isNaN(parseFloat(plotInfo.labor_detail[i].qty)) == false)
                                        qty = plotInfo.labor_detail[i].qty;
                                    else
                                        qty = plotInfo.labor_detail[i].labor_qty;
                                    plotInfo.labor_detail[i].price_sum = parseFloat(plotInfo.price) * parseFloat(qty);
                                    sum += plotInfo.labor_detail[i].price_sum;
                                }
                                if (sum > 0)
                                    plotInfo.price_sum = sum.toFixed(2);
                                break;
                            //計時
                            case "1":
                                var sum = 0;
                                for (var i in plotInfo.labor_detail) {
                                    var time = plotInfo.labor_detail[i].labor_time;
                                    plotInfo.labor_detail[i].price_sum = parseFloat(plotInfo.price) * parseFloat(time);
                                    sum += plotInfo.labor_detail[i].price_sum;
                                }
                                if (sum > 0)
                                    plotInfo.price_sum = sum.toFixed(2);
                                break;
                        }
                    }
                }


                //20210330 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                //查詢 數量分攤方式 的設定值
                function Quantity_Allocation_info_get() {
                    $MMWService.pageNumberInfoGet({
                        page_mode: 'Quantity_Allocation_info_get',
                        query_condition_info: [
                            { column_name: 'Equipmentno', query_mode: '0', value: machine_no, merge_condition_model: 'AND' }
                        ]
                    }, function (data) {
                        OutQtyOption = data[0].outqtyoption;
                    });
                }

                //回到出站畫面
                function backToTrackOut(dialog) {
                    if (dialog.mode == 'badReason') {
                        dialog.select_detail.abnormal_detail = abnormal_detail_backup.slice();
                        abnormal_detail_backup = [];
                        dialog.tmpBadReason = '';
                        dialog.tmpdefect_qty = '';
                    } else if (dialog.mode == 'multiple') {
                        dialog.select_detail.labor_detail = angular.merge([], labor_detail_backup);
                        labor_detail_backup = [];
                        dialog.tmpLabor_no = '';
                    } else if (dialog.mode == 'production_inf') {
                        dialog.plotData.production_inf_detail = angular.merge([], production_inf_detail_backup);
                        production_inf_detail_backup = [];
                    }
                    //dialog.select_detail = undefined;
                    dialog.mode = 'trackout';
                }

                //準備出站
                function prepareTrackout(dialog, feedback) {
                    var content = {};

                    content.report_datetime = dialog.plotData.sysdate_time;
                    content.check_out_mode = '1';
                    content.check_out_type = '2';
                    content.plot_info_detail = [];
                    //20171121 add by Dustdusk for M#0042498:出站新增[生產資料收集]功能
                    content.production_inf_type = dialog.plotData.production_inf_type;
                    content.production_inf_detail = dialog.plotData.production_inf_detail;
                    content.label_no = dialog.plotData.label_no;
                    content.production_inf_type = dialog.plotData.production_inf_type;
                    content.production_inf_detail = dialog.plotData.production_inf_detail;
                    //dialog.plot_info_detail.forEach(function(workstation){
                    for (var key in dialog.plot_info_detail) {
                        var workstation = dialog.plot_info_detail[key];
                        var plot_detail = {};

                        plot_detail.report_datetime = content.report_datetime;
                        plot_detail.machine_no = machine_no;
                        plot_detail.defect_qty = workstation.total_defect_qty,//20200604 新增不良數和短缺數到下一頁
                            plot_detail.lack_qty = workstation.total_lack_qty,//20200604 新增不良數和短缺數到下一頁
                            plot_detail.plot_no = workstation.plot_no;
                        plot_detail.op_no = workstation.op_no;
                        plot_detail.workstation_no = '';
                        plot_detail.qty = workstation.check_out_qty;
                        plot_detail.machine_hours = workstation.machine_hours;
                        plot_detail.number_of_operators = workstation.number_of_labor;
                        plot_detail.labor_hours = workstation.labor_hours;
                        plot_detail.plot_stamp = workstation.plot_stamp;
                        plot_detail.product_no = workstation.product_no;
                        plot_detail.product_ver = workstation.product_ver;
                        plot_detail.process_no = workstation.process_no;
                        plot_detail.process_ver = workstation.process_ver;
                        plot_detail.abnormal_detail = workstation.abnormal_detail ? workstation.abnormal_detail : [];
                        plot_detail.subop_employee_detail = [];
                        plot_detail.materials_detail = [];
                        workstation.materials_detail.forEach(function (item) {
                            // 20201215 add FOR #83685
                            var materials_detail = {
                                materials_no: item.sub_materials_no,
                                materials_plot_no: item.materials_plot_no,
                                actual_use_qty: dialog.autoReworkMaterialProcess == "2" ? 0 : item.use_qty,
                            }
                            plot_detail.materials_detail.push(materials_detail);
                        });
                        if (dialog.parent != 'B0214') {
                            workstation.labor_detail.forEach(function (labor) {
                                var tempLabor = {
                                    employee_no: labor.labor_no,
                                    work_time: labor.labor_time
                                };
                                if (!labor.qty) {
                                    tempLabor.qty = workstation.check_out_qty;
                                } else {
                                    tempLabor.qty = labor.qty;
                                }

                                tempLabor.parameter_value = labor.ParameterValue;//系数�

                                plot_detail.subop_employee_detail.push(tempLabor);
                            });
                        }
                        plot_detail.wait_reason_detail = dialog.plotData.wait_reason_detail;
                        plot_detail.sub_product_detail = [];
                        dialog.plotData.sub_product_detail.forEach(function (item) {
                            if ((+item.sub_product_qty) == 0)
                                return;

                            plot_detail.sub_product_detail.push(item);
                        });
                        //20220318 add by 翰鴻 for M#107697
                        var price_rate_list = [];
                        for (var i in workstation.labor_detail) {
                            var price_rate_obj = {};
                            price_rate_obj.acc = workstation.labor_detail[i].labor_no;
                            price_rate_obj.price_rate = workstation.labor_detail[i].PriceRate;
                            price_rate_list.push(price_rate_obj);
                        }
                        plot_detail.price_rate_list = price_rate_list;
                        plot_detail.price = workstation.price;
                        plot_detail.price_type = workstation.price_type;
                        content.plot_info_detail.push(plot_detail);
                    }

                    if (content.plot_info_detail.length != 0) {
                        if (feedback)
                            feedback(content, dialog);
                    } else {
                        $rootScope.showAlert($filter('translate')('B0219.msg.column7'));
                    }
                }

                //出站
                function trackout(content, dialog) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_check_out_process',
                        content: content,
                        success: function (data, response) {
                            $rootScope.showToast(response.Message);
                            dialog.hide();
                            //20200103 add by Dustdusk for M#66703: 增加出站後呼叫bartender
                            $timeout(function () {
                                // 執行標籤列印 
                                if (data.command_lines && data.command_lines.length > 0) {
                                    printLabel(0, data.command_lines);
                                }
                                // 執行 PDF列印
                                if (data.runcard_pdf_get && data.runcard_pdf_get.length > 0) {
                                    pdf_url = data.runcard_pdf_get[0].url_pdf;
                                    if (pdf_url.indexOf('http://') == -1) {
                                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                                    }
                                    print(pdf_url);
                                }
                            }, 200);

                            if (feedback)
                                feedback();
                        }
                    });
                }

                //良品數檢�?
                function goodQtyCheck(dialog, callback) {
                    var msg = '';
                    dialog.plotData.workstation_detail.forEach(function (plot) {
                        if (plot.checked && plot.good_qty < 0) {
                            if (msg != '')
                                msg += '<br>';
                            msg += $filter('translate')('B0219.msg.good_qty_less_than_zero', { plot_no: plot.plot_no });
                        }
                    });

                    if (msg != '') {
                        $rootScope.showAlert(msg);
                    } else {
                        if (callback)
                            callback();
                    }
                }
                //20170519 modify by Dustdusk for 將要出站的資料存進另外一個陣列dialog.plot_info_detail
                function ProductionParametersCheckProcess(dialog) {
                    //檢查 組合
                    var content = {
                        handle_type: 'CHECK_OUT',
                        recordlist: []
                    };
                    var workstation_detail_length = 0;//出站批數
                    var laborDetailCheckMsg = ''; //上工人員檢查結果
                    dialog.plot_info_detail = {};
                    dialog.plotData.workstation_detail.forEach(function (workstation) {
                        if (workstation.checked) {
                            content.recordlist.push({
                                plot_no: workstation.plot_no,
                                op_no: workstation.op_no,
                                qty: workstation.check_out_qty,
                                abnormal_detail: workstation.abnormal_detail,
                                machine_no: machine_no,
                                status: '1',
                                op_plug_in_detail: [
                                    {
                                        op_plug_in: dialog.op_plug_in,
                                        heat_plot_no: dialog.heat_plot_no
                                    }
                                ]
                            });

                            if (workstation.labor_detail.length == 0) {
                                laborDetailCheckMsg += $filter('translate')('B0219.msg.column9', { plot_no: workstation.plot_no }) + '<br>';
                            }
                            workstation_detail_length++;

                            //將要出站的資料先清空暫停原因再放入map裡面
                            workstation.wait_reason_detail = undefined;
                            //20180223 modify by Dustdusk
                            workstation.total_surplus_qty = workstation.total_surplus_qty || 0;
                            dialog.plot_info_detail[workstation.plot_no + ';' + workstation.op_no] = workstation;
                        }
                    });

                    if (workstation_detail_length == 0) {
                        $rootScope.showAlert($filter('translate')('B0219.msg.column7'));
                    } else if (laborDetailCheckMsg != '') {
                        $rootScope.showAlert(laborDetailCheckMsg);
                    } else {
                        SMES_AccLifeCheck(content.recordlist, function () {
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.production_parameters_check_process',
                                content: content,
                                success: function (data) {
                                    checkRule(data.query_result, dialog);
                                }
                            });
                        });
                    }
                }

                //rule_result : WARNNING / WAIT / PASS
                //20170517 modify by Dustdusk for SMES_ProductionParametersCheckProcess調整回傳內容
                function checkRule(query_result, dialog) {
                    var warnning_msg = '';
                    query_result.forEach(function (plot_rule) {
                        var plot_warnning_msg = '';
                        plot_rule.rule_detail.forEach(function (rule_detail) {
                            if (rule_detail.rule_result == 'WARNNING') {
                                if (plot_warnning_msg == '') {
                                    plot_warnning_msg = plot_rule.plot_no + ',' + plot_rule.op_no + '<br>';
                                }
                                plot_warnning_msg += rule_detail.rule_message + '<br>';
                            } else if (rule_detail.rule_result == 'WAIT') {
                                //在plot_info_detail內將wait_reason_detail初始化，有初始化的資料就表示日後要填入資�?
                                //20181005 modify by Dustdusk for 寫入暫停原因
                                dialog.plot_info_detail[plot_rule.plot_no + ';' + plot_rule.op_no].wait_reason_detail = [{ reason_no: 'Z901' }];
                            }
                        });
                        warnning_msg += plot_warnning_msg;
                    });

                    if (warnning_msg != '') {
                        $rootScope.showConfirm(warnning_msg,
                            function (dialog2) {
                                dialog2.hide();
                                prepareTrackout(dialog, trackout);
                            }
                        )
                    } else {
                        prepareTrackout(dialog, trackout);
                    }
                }

                //取得例外分類
                function genBadType(badReasonList, ori_badReasonList) {
                    var badTypeList = {},
                        return_list = [];
                    ori_badReasonList.forEach(function (badReason) {
                        var temp = $filter('filter')(badReasonList, { reason_no: badReason.abnormal_no }, true);
                        if (temp.length > 0) {
                            temp[0].chosen = 'Y';
                        }
                    });
                    badReasonList.forEach(function (badReason) {
                        if (badTypeList[badReason.reason_type]) {
                            badTypeList[badReason.reason_type].badReason_list.push(badReason);
                        } else {
                            badTypeList[badReason.reason_type] = {
                                reason_type: badReason.reason_type,
                                reason_sub_type: badReason.reason_sub_type,
                                badReason_list: [badReason]
                            }
                        }
                    });
                    return $rootScope.getValueforObj(badTypeList);
                }
                // 取出不良原因
                function BadReasonPick(badTypeList, reason_no) {
                    for (var i = 0; i < badTypeList.length; i++) {
                        var _temp = $filter('filter')(badTypeList[i].badReason_list, { reason_no: reason_no }, true);
                        if (_temp.length > 0) {
                            return _temp[0];
                        }
                    };
                }
                //透過batender 打印標籤
                function printLabel(index, commandlines) {
                    if (commandlines && index < commandlines.length) {
                        if (window.nodeRequire) {
                            try {
                                var exec = window.nodeRequire('child_process').exec;
                                exec(commandlines[index], function (error, stdout, stderr) {
                                    if (error) {
                                        console.error(error);
                                        $rootScope.showAlert($filter('translate')('B0206.msg.command_error', { error: error }));
                                    }
                                    index = index + 1;
                                    printLabel(index, commandlines);
                                });
                            } catch (e) {
                                console.error(e);
                                $rootScope.showAlert($filter('translate')('B0206.msg.cant_execute_bartender_command', { command: commandlines[index] }));
                            }
                        }
                    }
                }

                // PDF列印
                function print(pdf_url) {
                    if (window.nodeRequire) {
                        var sumatraPDF = window.nodeRequire('sumatra-pdf');
                        if (sumatraPDF) {
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try {
                                RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                            } catch (e) {
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if (!fs.existsSync(RuncardPath)) {
                                fs.mkdirSync(RuncardPath);
                            }

                            // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                            // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                            fs.readdirSync(RuncardPath, (err, files) => {
                                if (err) {
                                    console.log(err);
                                }
                                //listing all files using forEach
                                files.forEach((file) => {
                                    // Do whatever you want to do with the file
                                    fs.unlink(RuncardPath + '/' + file, (err) => {
                                        if (err) {
                                            console.debug(err);
                                        }
                                    })
                                });
                            })

                            // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                            let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                            $rootScope.downloadFile(pdf_url, pdfPath, function (dist_path) {
                                $rootScope.showLoading();
                                window.nodeRequire('sumatra-pdf').printWithSettings({
                                    path: dist_path,
                                    success: function () {
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                    },
                                    error: function (error) {
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                        //console.error(error);
                                    }
                                });
                            });
                        } else {
                            window.frames['kmi-pdf-panel'].pdf_print();
                        }
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                };
                //模製具壽命檢查
                function SMES_AccLifeCheck(recordlist, callback) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_ACC.acc_life_check_process',
                        content: { recordlist: recordlist },
                        success: function (data) {
                            if (data.life_manage == '0') {
                                //警示
                                $rootScope.showConfirm(data.description, function (confirmDialog) {
                                    confirmDialog.hide();
                                    if (callback)
                                        callback();
                                });
                            } else if (data.life_manage == '1') {
                                //暫停生產
                                $rootScope.showAlert(data.description);
                            } else if (data.life_manage == '2') {
                                //核准
                                if (callback)
                                    callback();
                            }
                        }
                    });
                }

                //生產信息收集檢查
                function productionInfValidate(production_inf_detail) {
                    var msg = '';
                    production_inf_detail.forEach(function (item) {
                        if (item.productioninf_value == undefined || item.productioninf_value == '') {
                            msg += $filter('translate')('B0219.msg.productioninf_value_empty', item) + '<br>';
                        }
                    });
                    return msg;
                }

                // 物料用量初始化
                function reCalcMaterialUseQty(plot, sum_qty) {
                    if (plot && plot.materials_detail) {
                        var materials_detail = plot.materials_detail;
                        var materialsMap = {};

                        for (var i = 0; i < materials_detail.length; i++) {
                            var materials = materials_detail[i];

                            if (!materialsMap[materials.materials_no]) {
                                var materialsList = $filter('filter')(materials_detail, { materials_no: materials.materials_no }, true);

                                if (materialsList.length > 0) {
                                    var need_qty = +sum_qty; //出站所需要的物料用量

                                    // 20200525 modify by WeiTing for M#72260 - 透過後台傳回參數 Num_Of_Decimal 調整小數點位數，一般是不開放調整的，除非有特殊需求才請後端直接調整資料庫。
                                    var Num_Of_Decimal = +plot.Num_Of_Decimal;

                                    // 20201005 modify by WeiTing for M#67681 - 透過後台傳回參數 Close_DecreaseRate，判斷是否關閉損耗率(decrease_rate)計算。
                                    var Close_DecreaseRate = false;
                                    if (plot.Close_DecreaseRate) {
                                        Close_DecreaseRate = true;
                                    }

                                    materialsList.forEach(function (item, index) {
                                        // 物料實際耗用量 = 物料可用量 / 標準用料 / (1 + 損耗量)
                                        var real_use_qty = (((+item.available_qty) / (+item.std_use_qty)) / $calculater.decimalAdd(1, +item.decrease_rate));
                                        if (Close_DecreaseRate) {
                                            real_use_qty = ((+item.available_qty) / (+item.std_use_qty));
                                        }

                                        if (+real_use_qty < +need_qty) {
                                            // 物料預設使用量 = 可用量
                                            use_qty = (+item.available_qty); // 使用量結果
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            item.use_qty = Math.floor(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); // 調整使用量結果的小數點位數
                                            need_qty = $calculater.decimalSub(+need_qty, +real_use_qty); // 更新出站所需要的物料用量
                                        } else {
                                            // 物料預設使用量 = 剩餘的物料所需用量 * 標準用量 * (1 + 損耗量)
                                            use_qty = $calculater.decimalMutiple($calculater.decimalMutiple(+need_qty, +item.std_use_qty), $calculater.decimalAdd(1, +item.decrease_rate)); // 使用量結果
                                            if (Close_DecreaseRate) {
                                                use_qty = $calculater.decimalMutiple(+need_qty, +item.std_use_qty); // 使用量結果
                                            }
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            item.use_qty = Math.floor(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); // 調整使用量結果的小數點位數
                                            need_qty = 0; //出站所需要的物料用量已足夠
                                        }

                                        // 20200211 modify by WeiTing for M#66921 - 修改扣料順序邏輯：
                                        // 1. 主料存量優先扣除 
                                        // 2. 替代料存量依序扣除 
                                        // 3. 全部存量扣除完，需求量仍 > 0，則將量加回主料扣除量。（一般料與倒扣料一致）
                                        // 最後，出站所需要的物料用量仍不足夠，將仍不足的量加在第一筆物料(出站才會出現物料不足，不允許出站)
                                        if (index == (materialsList.length - 1) && +need_qty > 0) {
                                            need_qty = $calculater.decimalMutiple($calculater.decimalMutiple(+need_qty, +materialsList[0].std_use_qty), $calculater.decimalAdd(1, +materialsList[0].decrease_rate));
                                            if (Close_DecreaseRate) {
                                                need_qty = $calculater.decimalMutiple(+need_qty, +materialsList[0].std_use_qty);
                                            }
                                            use_qty = $calculater.decimalAdd(+materialsList[0].use_qty, +need_qty); // 使用量結果
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            materialsList[0].use_qty = Math.floor(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); // 調整使用量結果的小數點位數
                                        }
                                    });
                                }
                                materialsMap[materials.materials_no] = true;
                            }
                        }
                    }
                }

                function check(feedback){
                        var isConfirm =false;
                        $rootScope.showConfirm($filter('translate')('A08.msg.msg1'), function (dialog1) {
                            dialog1.hide();
                            isConfirm =true;
                        });
                        if(feedback)
                            feedback();

                }

                // 20221011 modify by Alan for#118808 : 重構
                //檢查人時是否為0
                function checkLaborDetail({data, reworkMethod, opPlugInDetail}, callback) {
                    var temp = $filter('filter')(data.workstation_detail, function (x) { return x.labor_detail.length == 0; });

                    if (temp.length > 0) {
                        // 0080212: [sMES] 無法出站，出現人員尚未上工，不允許執行 [世同]
                        $rootScope.showConfirm($filter('translate')('B0219.msg.column11'), function (di) {
                            di.hide();

                            data.workstation_detail.forEach(e => {
                                if (e.labor_detail.length == 0) {
                                    e.labor_detail.push({ labor_no: config.cache.account, labor_name: config.cache.name, qty: 0, _labor_time: 0, labor_time: 0 });
                                }
                            });

                            //後續作業
                            if(typeof callback === 'function') {
                                callback({data, reworkMethod, opPlugInDetail});
                            }
                        });
                    } else if(typeof callback === 'function') {
                        callback({data, reworkMethod, opPlugInDetail});
                    }
                }

                // 20221011 modify by Alan for#118808 : 重構
                //20210607 Add by Tim for#增加SQL實體分頁功能：將抓資料的程式獨立出來.
                function GetPlotInfoData(isFirstTime, param, callback) {
                    var plotItem_workstation_no = '';
                    if (parent) {
                        if (parent == 'B0201') {
                            plotItem_workstation_no = machine_no;
                        } else {
                            plotItem_workstation_no = '';
                        }
                    }

                    var content = {
                        machine_no: "machine_no",
                        plot_no: plotItem.plot_no,
                        op_no: plotItem.op_no,
                        workstation_no: plotItem_workstation_no,
                        qty: plotItem.qty,
                        mode: parent == 'B0214' ? '1' : undefined,
                        return_type: 4,
                        op_plug_in: plotItem.op_plug_in,
                        pageSetting: pageSetting, //20210607 Add by Tim for#增加SQL實體分頁功能：記錄分頁資訊.
                        lot_no: plot_no, // 20220810 add by zhuyuchao for#添加查询条件
                        product_no: '',
                        product_name: '',
                    };

                    // 20220810 add by zhuyuchao for#添加查询条件
                    if (param != undefined) {
                        content.lot_no = param.lot_no;
                        content.product_no = param.product_no;
                        content.product_name = param.product_name;
                        content.op_name = param.op_name;
                        content.item_spec = param.item_spec;
                        content.op_no_like = param.op_no_like;
                    }

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_info_get',
                        content: content,
                        success: function (data) {
                            var reworkMethod = "1";
                            // 20201214 modify by 外包 for M#83685: 重工批重复扣料多模式选择。
                            if (data.auto_rework_material_process) {
                                reworkMethod = data.auto_rework_material_process;
                            }

                            // 爐批號 opPlugInDetail
                            var opPlugInDetail;
                            if (!data.op_plug_in_detail || data.op_plug_in_detail.length == 0)
                                opPlugInDetail = [];
                            else
                                opPlugInDetail = data.op_plug_in_detail[0];
                            
                            let plot_info_get_totalPage = data.plot_info_get_totalPage
                            data = data.plot_info_get[0];
                            data.wait_reason_detail = [];
                            // 20210427 modify by 14169 for M#91283: 把過濾後的狀態R的生產批帶到批次出站裡做判斷。
                            var workstation_detail = data.workstation_detail;
                            // var filter_workstation_detail = [];
                            // for (var i = 0; i < workstation_detail.length; i++) {
                            //     for (var j = 0; j < plot_list.length; j++) {
                            //         if (workstation_detail[i].plot_no === plot_list[j].plot_no) {
                            //             filter_workstation_detail.push(workstation_detail[i]);
                            //             // 20211116 alan M#0102792: [sMES]平行製程不同作業站在同一機台R，批次出站資料重複[宏毅]
                            //             // 過濾後未中止迴圈，導致重複加入
                            //             break;
                            //         }
                            //     }
                            // }
                            data.workstation_detail = workstation_detail;
                            //M#95547 for a991241234 生產批派工合併註記勾選
                            if (plotItem.batch_mark && plotItem.batch_mark.trim() != '') {
                                var fliter_query = {};                              //合併註記篩選條件
                                fliter_query.batch_mark = plotItem.batch_mark;      //合併註記 tag
                                fliter_query.op_no = plotItem.op_no;                //作業站
                                fliter_query.status = plotItem.status;              //生產批狀態  
                                var has_mark_lot = $filter('filter')(plot_list, fliter_query);
                                if (has_mark_lot.length > 1) {
                                    for (var i in data.workstation_detail) {
                                        var lot_query = {};
                                        lot_query.plot_no = data.workstation_detail[i].plot_no;
                                        lot_query.op_no = data.workstation_detail[i].op_no;
                                        var same_mark_lot = $filter('filter')(has_mark_lot, lot_query);
                                        if (same_mark_lot && same_mark_lot.length > 0)
                                            data.workstation_detail[i].checked = true;
                                    }
                                }
                            }
                            if (data.workstation_detail && data.workstation_detail.length > 0) {
                                data.workstation_detail.forEach(function (plot) {
                                    plot.good_qty = plot.check_out_qty;
                                    plot.qty = plot.check_out_qty;
                                    //計算不良原因總數
                                    plot.total_defect_qty = 0;//報廢
                                    plot.total_surplus_qty = 0;//多餘
                                    plot.total_lack_qty = 0;//短少
                                    if (plot.abnormal_detail) {
                                        plot.abnormal_detail.forEach(function (abnormal_detail) {
                                            if (abnormal_detail.abnormal_type == '11') {
                                                plot.total_surplus_qty = $calculater.decimalAdd((+plot.total_surplus_qty), (+abnormal_detail.defect_qty));
                                            } else if (abnormal_detail.abnormal_type == '12') {
                                                plot.total_lack_qty = $calculater.decimalAdd((+plot.total_lack_qty), (+abnormal_detail.defect_qty));
                                            } else {
                                                plot.total_defect_qty = $calculater.decimalAdd((+plot.total_defect_qty), (+abnormal_detail.defect_qty));
                                            }
                                        });
                                    }
                                    //良品�?= 『出站數量�?- 『不良品�?- 『短少�?+ 『多餘�?
                                    plot.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+plot.good_qty), (+plot.total_surplus_qty)), (+plot.total_defect_qty)), (+plot.total_lack_qty));
                                    //2018051601 modify by Dustdusk for M#45925:
                                    //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                    plot.Num_Of_Decimal = data.Num_Of_Decimal;
                                    plot.Close_DecreaseRate = data.Close_DecreaseRate;
                                    var sum_qty = $calculater.decimalAdd((+plot.qty), (+plot.total_surplus_qty));
                                    reCalcMaterialUseQty(plot, sum_qty);
                                    //20220328 add by 翰鴻 for M#107697

                                    getPriceSum(plot);
                                    getPriceSumByLabor(plot);
                                });
                            }

                            //20210607 Add by Tim：增加SQL實體分頁功能.
                            setPageSetting(data.workstation_detail, plot_info_get_totalPage);

                            //20210607 Modify by Tim for#增加SQL實體分頁功能：切換分頁時不執行checkLaborDetail.
                            if (isFirstTime) {
                                checkLaborDetail({data, reworkMethod, opPlugInDetail}, callback);
                            }
                        }
                    });
                }

                //20210607 Add by Tim：增加SQL實體分頁功能.
                function setPageSetting(list, plot_info_get_totalPage) {
                    if (list) {
                        if (pageSetting) {
                            if (list.length != 0) {
                                if (plot_info_get_totalPage <= 0 || plot_info_get_totalPage == "" || plot_info_get_totalPage == undefined)
                                    pageSetting.TotalPage = 1;
                                else
                                    pageSetting.TotalPage = plot_info_get_totalPage;

                                if (pageSetting.PageNumber > pageSetting.TotalPage) {
                                    pageSetting.PageNumber = pageSetting.TotalPage;
                                }
                            } else {
                                pageSetting.TotalPage = 1;
                                pageSetting.PageNumber = 1;
                            }
                        }
                    }
                }

                // 取得要出站的批號
                (function plotInfoGet() {
                        openDialog(); 
                    /*20210607 Modify by Tim for#增加SQL實體分頁功能：往外拉成共用方法.
                    var plotItem_workstation_no = '';
                    if(parent) {
                        if(parent == 'B0201'){
                            plotItem_workstation_no = machine_no;
                        } else {
                            plotItem_workstation_no = '';
                        }
                    } */

                    //20210330 Modify by德義家興for#86664: 使用批次出站的报工未能按照设备基本资料设定的均分出站数分摊多人上工的数量
                    //開窗前就查出設備 數量分攤方式 的設定值 (開窗後設備已固定)
                  //  Quantity_Allocation_info_get();

                    //20210607 Modify by Tim for#增加SQL實體分頁功能：往外拉成共用方法.
                //     GetPlotInfoData(true, undefined, function(info) {
                //         openDialog(info);
                //     });
                })();
            };
        }]);
});
